package com.mall.utils.encrypt;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * 用于加密使用
 */
public class RSA {
    public static final String KEY_ALGORITHM = "RSA";
    /** 貌似默认是RSA/NONE/PKCS1Padding，未验证 */
    public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
    public static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgkVcTvuPVv4XhhLJ2AOoKJBI91iBhaiwDWk+wGlPqjCBz9nVyYNvEEB9CJrmMFMzxyYYs59JYHrGF941UJ2hpxep5W3LcbIsMILSWKte2dhPk7ufd5XDZWtGEiLBlisuPDwsB7V0hcVG4f/Om+hagKwUkAfFPqDD3ADMhAeYOkR55dokqyzemT6P7/MiITY5giL6xqg4uWYhr9mcCpn41ItKhJ5FiBfkFha+pzLHQou0A9jNjVUZIE9eaWiMm1Vd46aKHAy66rfbGpLCT8E+wT/7MxGmzfcLljY7ZFPw9mMmNOICnSvm6ELTrXzUi8Ze2oLk55nW7rthcccHP6ygTQIDAQAB";
    public static final String PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCCRVxO+49W/heGEsnYA6gokEj3WIGFqLANaT7AaU+qMIHP2dXJg28QQH0ImuYwUzPHJhizn0lgesYX3jVQnaGnF6nlbctxsiwwgtJYq17Z2E+Tu593lcNla0YSIsGWKy48PCwHtXSFxUbh/86b6FqArBSQB8U+oMPcAMyEB5g6RHnl2iSrLN6ZPo/v8yIhNjmCIvrGqDi5ZiGv2ZwKmfjUi0qEnkWIF+QWFr6nMsdCi7QD2M2NVRkgT15paIybVV3jpoocDLrqt9saksJPwT7BP/szEabN9wuWNjtkU/D2YyY04gKdK+boQtOt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YBlgW+9KUpWgnD4m/dqZanipzDrNHGYl8Ycysb3Pg1ux752/7baa/ZjAj7NDvIs8cdPjPngT6gHzC1UMrVyUvawk1iOofTWUy662yIDmbItuhcMrQRNT2nrasSBI7yqg5gpsS9hYg1xR5mpI5DFAgapoujdBk8zDWRr+r00XPOl8g==";


    public static void main(String[] args) throws UnsupportedEncodingException {
        String lisence="sAG1yrA";
        System.out.println(lisence);
        System.out.println("长度（不大于245） >>> "+ lisence.getBytes().length);
        String encodeText=RSAEncode(KeyGenerator.getPublicKey(PUBLIC_KEY),lisence);
        System.out.println("加密 >>> "+encodeText);
        String decodeText=RSADecode(KeyGenerator.getPrivateKey(PRIVATE_KEY),encodeText);
        System.out.println("解密 >>> "+decodeText+" >>> "+decodeText.equals(lisence));
    }


    /**
     * 还原私钥，PKCS8EncodedKeySpec 用于构建私钥的规范
     *
     * @param keyBytes
     * @return
     */
    public static PrivateKey restorePrivateKey(byte[] keyBytes) {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                keyBytes);
        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = factory
                    .generatePrivate(pkcs8EncodedKeySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密，三步走。
     *
     * @param key
     * @param text
     * @return
     */
    public static String RSAEncode(PublicKey key, String text) {

        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encodeByte= cipher.doFinal(text.getBytes());
            return new String(java.util.Base64.getEncoder().encode(encodeByte));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 解密，三步走。
     *
     * @param key
     * @param encodedText
     * @return
     */
    public static String RSADecode(PrivateKey key, String encodedText) {

        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
           // return new String(cipher.doFinal(Base64.decodeBase64(encodedText)));
            return new String(cipher.doFinal(java.util.Base64.getDecoder().decode(encodedText.getBytes())));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }


}